package priv.pfz.basedao.jdbctemplate.dao.impl;

import priv.pfz.basedao.jdbctemplate.SqlResult;
import priv.pfz.basedao.jdbctemplate.dao.DefaultBaseDao;
import priv.pfz.basedao.jdbctemplate.sqlprovider.CountSqlProvider;
import priv.pfz.basedao.jdbctemplate.sqlprovider.DeleteSqlProvider;
import priv.pfz.basedao.jdbctemplate.sqlprovider.ListSqlProvider;
import priv.pfz.basedao.jdbctemplate.sqlprovider.UpdateSqlProvider;
import priv.pfz.basedao.pagequery.Page;
import priv.pfz.basedao.query.BaseQuery;

import javax.annotation.Nonnull;
import java.util.List;

/**
 * @author yyjxp
 * 2024/8/4 19:39
 */
public class DefaultBaseDaoImpl<Entity, Query extends BaseQuery<Query>> extends SimpleBaseDaoImpl<Entity>
        implements DefaultBaseDao<Entity, Query> {
    @Override
    public int update(@Nonnull Entity entity, @Nonnull Query query) {
        SqlResult sqlResult = UpdateSqlProvider.provideSql(entity, query, null, daoInfo);
        return jdbcTemplate.update(sqlResult.getSqlTemplate(), sqlResult.getArgs());
    }

    @Override
    public int count(@Nonnull Query query) {
        SqlResult sqlResult = CountSqlProvider.provideSql(query, null, daoInfo);
        return jdbcTemplate.queryForObject(sqlResult.getSqlTemplate(), sqlResult.getArgs(), int.class);
    }

    @Override
    public List<Entity> list(@Nonnull Query query) {
        SqlResult sqlResult = ListSqlProvider.provideSql(query, null, daoInfo);
        return jdbcTemplate.query(sqlResult.getSqlTemplate(), rowMapper, sqlResult.getArgs());
    }

    @Override
    public int delete(@Nonnull Query query) {
        SqlResult sqlResult = DeleteSqlProvider.provideSql(query, null, daoInfo);
        return jdbcTemplate.update(sqlResult.getSqlTemplate(), sqlResult.getArgs());
    }

    @Override
    public Page<Entity> pageQuery(@Nonnull Query query) {
        int count = count(query);
        List<Entity> entities = list(query);
        int totalPage = (int) Math.ceil((double) count / query.getPageSize());
        return new Page<>(query.getPageNo(), query.getPageSize(), count, totalPage, entities);
    }
}
